package admin

import (
	"gitee.com/extrame/tujiang/http"
	"gitee.com/extrame/tujiang/http/model"
	"github.com/extrame/goblet"
	"github.com/extrame/goblet/plugin"
)

type User struct {
	goblet.Route `prefix:"/admin/v1/user"`
	Config       *http.Config
}

func (u *User) Login(ctx *goblet.Context, args *model.User) error {

	args.EncryptPassword(u.Config.Salt)

	has, _ := goblet.DB.Where("username = ? AND password = ?", args.Username, args.Password).Get(&args)

	if !has {
		return http.NotLoginedError
	}
	ctx.AddLoginId(args.Id)
	return nil
}

func (u *User) Logined(ctx *goblet.Context) error {
	_, ok := ctx.GetLoginId()
	if !ok {
		return http.NotLoginedError
	}
	return nil
}

func (u *User) Update(ctx *goblet.Context, args *model.User) error {
	args.EncryptPassword(u.Config.Salt)
	updated, err := goblet.DB.Where("username = ?", args.Username).Update(args)
	if err != nil {
		return plugin.WrapError(20001, err)
	} else if updated == 0 {
		return http.NoSuchUserError
	}
}
